/**
 * 监听剪切板中写入的内容，是否含有对应配置的app分享链接，如果有则打开对应app
 */
const appList = {
    "手机淘宝": {packageName: 'com.taobao.taobao', keys: ['τáǒЬáǒ', 'τаo宝', '手机淘宝', '淘♂寳']},
    "京喜": {packageName: 'com.jd.pingou', keys: ['【京xi喜App】', '【京囍App】','【京A囍pp】','【A京p喜p】','【京jing喜App】']},
    "京东金融": {packageName: 'com.jd.jrapp', keys: ['【亰 d0ng 金 融App】', '【Jing d0ng 金 融App】', '【椋 岽 jin 融 App】']},
    "京东": {packageName: 'com.jingdong.app.mall', keys: ['（京つ東）', '（京ㄇ東）', '【京ㄟ東】']}
};

let manager = context.getSystemService(context.CLIPBOARD_SERVICE);

manager.addPrimaryClipChangedListener(
  new android.content.ClipboardManager.OnPrimaryClipChangedListener({
    onPrimaryClipChanged: function () {
      if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
        let addedText = manager.getPrimaryClip().getItemAt(0).getText();
        if (addedText != null) {
          openAppForStr(addedText);
        }
      }
    },
  })
);

function getTextApp(text) {
    let key = '';
    for (appName in appList) {
        // console.log(appName)
        for (index in appList[appName].keys) {
            key = appList[appName].keys[index];
            // console.log(key)
            if (text.indexOf(key) > -1) {
                return appName;
            }
        }
    }    
}
function openAppForStr(str) {
    if (!str) {
        return;
    }
    log("剪切板: " + str);
    // 识别是否app 链接
    let appName = getTextApp(str);
    if (!appName) {
        console.log('未识别到app');
        return;
    }
    // log('识别到软件 ' + appName)
    // 打开对应app
    let packageName = appList[appName].packageName;
    // log("是否安装软件 " + packageName)
    if (packageName) {
        // log('申请提示')
        dialogs.confirm("剪切板助手", "是否打开 " + appName, (res) => {
            // log('是否可以打开' + JSON.stringify(res))
            if (res == true) {
                app.launch(packageName);
            }
        });
    }
}

setInterval(() => {}, 10000);